﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace LanUserSeeThroughRouter
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            LanUser.TimeSpan = 24;
            AllUsers.Add(new LanUser());
            //    webBrowser1.Navigate("http://localhost:6236/WebForm2.aspx");
            webBrowser1.ScriptErrorsSuppressed = true;
            webBrowser1.Navigate("http://192.168.1.1");

        }

        List<LanUser> allUsers = new List<LanUser>();
        public List<LanUser> AllUsers
        {
            get
            {
                return allUsers;
            }
            set
            {
                allUsers = value;
            }
        }


        void ControlThread()
        {
            while (!Stop)
            {
                if (isArpList)
                {
                    Thread.Sleep(20000);

                }
                else
                {
                    Thread.Sleep(4000);

                }
                this.Invoke(
               (Action)(() =>
                         {
                             dgUsers.DataSource = AllUsers;
                             dgUsers.Refresh();
                             if (AllUsers.Count != lastUserCount)
                             {
                                 //通知
                                 notifyIcon1.ShowBalloonTip(5000);
                                 lastUserCount = AllUsers.Count;
                             }
                             if (isArpList)
                             {
                                 isArpList = false;
                                 webBrowser1.Document.Window.Frames[4].Navigate(userStateUrl);
                             }
                             else
                             {
                                 isArpList = true;
                                 webBrowser1.Document.Window.Frames[4].Navigate(ArpBindingUrl);
                             }
                         })
               );
            }

        }
        private void btnbutton2_Click(object sender, EventArgs e)
        {
            HtmlElement ele = webBrowser1.Document.Window.Frames[4].Document.CreateElement("script");
            ele.SetAttribute("type", "text/javascript");

            ele.SetAttribute("text", @"  
 
       alert(arpClientListDyn);
      ");
            webBrowser1.Document.Window.Frames[4].Document.Body.AppendChild(ele);
        }

        private System.Threading.Timer t1;
        private System.Threading.Timer t2;

        private void btnbutton1_Click_1(object sender, EventArgs e)
        {
            isArpList = true;
            webBrowser1.Document.Window.Frames[4].Navigate(ArpBindingUrl);
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
            controlThread = new Thread(ControlThread) { IsBackground = true };
        }

        private Thread controlThread;
        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (isArpList)
            {
                this.Invoke(
                    (Action)(() =>
                    {
                        HtmlElement ele = webBrowser1.Document.Window.Frames[4].Document.CreateElement("script");
                        ele.SetAttribute("type", "text/javascript");
                        ele.SetAttribute("text", @"  
  function GetArpUser(i){
          var j=3*(i-1);
          if(j<arpClientListDyn.length-1)
          {
                 var mac= arpClientListDyn[j+1];
 var ip= arpClientListDyn[j+2];
                 return mac+','+ip;
          }
         
}

function GetArpUserCount(){         
         
                 return (arpClientListDyn.length-2)/3;       
         
}
      ");
                        try
                        {
                            webBrowser1.Document.Window.Frames[4].Document.Body.AppendChild(ele);

                            var userCount = (int)webBrowser1.Document.Window.Frames[4].Document.InvokeScript("GetArpUserCount") + 1;
                            if (first)
                            {
                                lastUserCount = userCount;
                                first = false;
                            }
                            for (int i = 0; i < userCount - 1; i++)
                            {
                                var userStr = (string)webBrowser1.Document.Window.Frames[4].Document.InvokeScript("GetArpUser", new object[] { i + 1 });
                                var data = userStr.Split(',');
                                LanUser lu = new LanUser()
                                                 {
                                                     IP = data[1],
                                                     Mac = data[0]
                                                 };
                                if (AllUsers.Where(u => u.Mac == lu.Mac).ToList().Count > 0)//一样的
                                {
                                    continue;
                                }

                                AllUsers.Add(lu);
                            }

                        }
                        catch
                        {


                        }

                    })
                    );
                if (Stop)
                {
                    Stop = false;
                    controlThread.Start();
                }


            }
            else //处理速度
            {
                this.Invoke(

                    (Action)(
                    () =>
                    {
                        HtmlElement ele = webBrowser1.Document.Window.Frames[4].Document.CreateElement("script");
                        ele.SetAttribute("type", "text/javascript");
                        ele.SetAttribute("text", @"  
  function GetUserState(i){
              var j=4*(i-1);
   if(j<hostList.length-1)
          {
                     var mac=hostList[j];
                 var recCount= hostList[j+2];
                 var sendCount= hostList[j+3];
                var state=wlanStatusStringArray[hostList[j+1]];
                 return  mac+','+state+','+recCount+','+sendCount;
          }
       
}
 function GetConnectedUserCount(){    
                 return (hostList.length-2)/4-1;  
}
         

      ");
                        try
                        {
                            webBrowser1.Document.Window.Frames[4].Document.Body.AppendChild(ele);
                            var wireUserCount = (int)webBrowser1.Document.Window.Frames[4].Document.InvokeScript("GetConnectedUserCount");
                            for (int i = 0; i < wireUserCount + 1; i++)
                            {
                                var wuserStr = (string)webBrowser1.Document.Window.Frames[4].Document.InvokeScript("GetUserState", new object[] { i + 1 });
                                var wdata = wuserStr.Split(',');
                                if (i == 0)//路由器
                                {
                                    AllUsers[0].Mac = wdata[0];
                                    AllUsers[0].RecPacketsCount = int.Parse(wdata[2]);
                                    AllUsers[0].SendPacketsCount = int.Parse(wdata[3]);
                                    AllUsers[0].State = wdata[1];
                                }
                                else
                                {
                                    foreach (var user in AllUsers)
                                    {
                                        if (user.Mac == wdata[0])//找到
                                        {
                                            user.RecPacketsCount = int.Parse(wdata[2]);
                                            user.SendPacketsCount = int.Parse(wdata[3]);
                                            user.State = wdata[1];
                                        }
                                    }
                                }

                            }
                        }
                        catch
                        {

                        }

                    })
                    );
            }

        }
        bool isArpList = true;
        private string userStateUrl = "http://192.168.1.1/userRpm/WlanStationRpm.htm";
        private string ArpBindingUrl = "http://192.168.1.1/userRpm/LanArpBindingListRpm.htm";

        private int lastUserCount;
        private bool first = true;
        private bool Stop = true;

        private void btnbutton2_Click_1(object sender, EventArgs e)
        {
            Stop = true;
        }

        private void webBrowser1_DocumentCompleted_1(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }

        private void frmMain_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Tplink = chkTPLink.Checked;
            timer1.Interval = 1000 * int.Parse(textBox2.Text);
            timer1.Start();



        }

        void webBrowser2_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            GetStatics();
        }



        private void GetStatics()
        {
            LanStaticsUser.Clear();
            Ession.PageJavaScriptRunner.RegisterFunction(
                webBrowser2.Document.Window.Frames[4].Document
                , @"
                  function GetStat()
                  {
                      return statList.toString() ;
                  }
");

            string stat = (string)webBrowser2.Document.Window.Frames[4].Document.InvokeScript("GetStat");
            var s = stat.Split(',');
            int userCount = GetUserCount(s);
            for (int i = 0; i < userCount; i++)
            {
                LanUser lu = GetUserStat(s, i);
                LanStaticsUser.Add(lu);
            }
            if (userCount > int.Parse(textBox1.Text))
            {
                LanStaticsUser.RemoveAt(int.Parse(textBox1.Text));
                string delUrl;
                if (Tplink)
                {
                    delUrl =
                 string.Format(
                     "http://192.168.1.1/userRpm/SystemStatisticRpm.htm?delone={0}&autoRefresh=1&sortType=1&Goto_page=1",
                     textBox1.Text);
                }
                else
                {
                    delUrl =
                string.Format(
                    "http://192.168.1.1/userRpm/SystemStatisticRpm.htm?delone={0}&autoRefresh=1&sortType=1",
                    textBox1.Text);
                }

                webBrowser2.Document.Window.Frames[4].Navigate(delUrl);
            }


            dataGridView1.DataSource = LanStaticsUser;
            dataGridView1.Refresh();
        }

        private LanUser GetUserStat(string[] s, int i)
        {
            LanUser lu = new LanUser();
            int j = i * 14;
            lu.IP = s[j + 1];
            lu.Mac = s[j + 2];
            lu.RecPacketsCount = int.Parse(s[j + 6]);
            return lu;
        }

        private int GetUserCount(string[] s)
        {
            return (s.Length - 2) / 14;
        }

        List<LanUser> LanStaticsUser = new List<LanUser>();
        private bool Tplink;
        private void button2_Click(object sender, EventArgs e)
        {
            // "http://192.168.1.1/userRpm/SystemStatisticRpm.htm?delone=4&interval=60&autoRefresh=1&sortType=1&Goto_page=1";
            webBrowser2.Navigate("http://192.168.1.1");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            webBrowser2.Document.Window.Frames[4].Navigate("http://192.168.1.1/userRpm/SystemStatisticRpm.htm");
            webBrowser2.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser2_DocumentCompleted);

        }


    }
}
